package com.shujia.flink.table

import java.time.LocalDateTime

import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment
import org.apache.flink.table.functions.ScalarFunction

object Demo8ProcTime {
  def main(args: Array[String]): Unit = {
    //创建flink 环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //设置table 环境的一些参数
    val bsSettings: EnvironmentSettings = EnvironmentSettings.newInstance()
      .useBlinkPlanner() //使用blikc计划器
      .inStreamingMode() //流模式
      .build()

    // 创建flink  table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    /**
      * 注册自定义函数
      *
      */

    bsTableEnv.createTemporaryFunction("addTime", new AddTime)

    /**
      * 在当前版本中PROCTIME()获取到的时间时区差了8小时，后面需要将时间增加8小时
      * 这个问题在新的版本中解决了
      *
      */
    bsTableEnv.executeSql(
      """
        |CREATE TABLE student (
        |  id STRING,
        |  name STRING,
        |  age INT,
        |  gender STRING,
        |  clazz STRING,
        |  user_action_time AS PROCTIME() -- 声明一个额外的列作为处理时间属性
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'student',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'testGroup',
        | 'format' = 'json',
        | 'scan.startup.mode' = 'earliest-offset'
        |)
        |
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |CREATE TABLE print_table (
        |  clazz STRING,
        |  win_end TIMESTAMP(3),
        |  c BIGINT
        |)
        |WITH ('connector' = 'print')
        |
      """.stripMargin)

    bsTableEnv.executeSql(
      """
        |insert into print_table
        |select
        |clazz,
        |addTime(TUMBLE_END(user_action_time, INTERVAL '5' SECOND)) as win_end,
        |count(1) as c
        |from student
        |group by
        |clazz,
        |TUMBLE(user_action_time, INTERVAL '5' SECOND)
        |
      """.stripMargin)

  }

}

/**
  * 自定义函数
  *
  */
class AddTime extends ScalarFunction {

  /**
    * 方法名必须是eval
    *
    * @param localDateTime : 时间戳在代码中的类型
    * @return
    */
  def eval(localDateTime: LocalDateTime): LocalDateTime = {
    //时间增加8小时
    localDateTime.plusHours(8)
  }
}
